﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using ZingBlog.Domain.Entities;
using ZingBlog.Dto;
using ZingBlog.IService;
using ZingBlog.Web.Areas.Admin.Controllers;
using ZingFrameworkCore.Common;

namespace ZingBlog.Web.Areas.Permissions.Controllers
{
    [Area("Permissions")]
    public class UserController : BaseController
    {
        public IUserService userService { get; set; }
        public IRoleService roleService { get; set; }
        public SelectList RoleList { get { return new SelectList(roleService.GetRoleList(), "Id", "RoleName"); } }
        // GET: Permissions/User
        public override ActionResult Index(int? id)
        {
            ViewBag.RoleId = RoleList;
            base.Index(id);
            return View();
        }
        /// <summary>
        /// 加载数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult List(UserEntity filter, PageInfo pageInfo)
        {
            var result = userService.GetListByFilter(filter, pageInfo);
            return Json(result);
        }
        public ActionResult Detail(int Id)
        {
            var model = userService.GetDetail(Id);
            return View(model);
        }
        public ActionResult Edit(int Id)
        {
            var model = userService.ReadEntity(Id);
            ViewBag.RoleId = RoleList;
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(UserEntity model)
        {
            model.UpdateOn = DateTime.Now;
            model.UpdateBy = Operator.UserId;
            var result = userService.UpdateEntity(model) ? SuccessTip() : ErrorTip();
            return Json(result);
        }
        public ActionResult Add()
        {
            ViewBag.RoleId = RoleList;
            return View();
        }
        [HttpPost]
        public ActionResult Add(UserEntity model)
        {
            model.CreateOn = DateTime.Now;
            model.CreateBy = Operator.UserId;
            model.PassWord=Md5.Crypt(Configs.GetValue("InitUserPwd"), Md5CryptType.Len32);
            var result = userService.CreateEntity(model) ? SuccessTip() : ErrorTip();
            return Json(result);
        }
        [HttpPost]
        public ActionResult Delete(int Id)
        {
            var result = userService.DeleteEntity(Id) ? SuccessTip() : ErrorTip();
            return Json(result);
        }
        [HttpPost]
        public ActionResult InitPwd(int Id)
        {
            var initPwd = Md5.Crypt(Configs.GetValue("InitUserPwd"),  Md5CryptType.Len32);
            var model = new UserEntity { Id = Id, PassWord = initPwd };
            var result = userService.InitPwd(model) ? SuccessTip() : ErrorTip();
            return Json(result);
        }
    }
}